package com.me.study.app.rvRichEditor.provider

import android.text.Editable
import android.text.Layout
import android.text.TextWatcher
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.EditText
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.me.study.R
import com.me.study.app.data.NotifyType
import com.me.study.app.data.RichEditorType
import com.me.study.app.rvRichEditor.RichEditorData
import com.me.study.app.rvRichEditor.listener.EditorCursorListener


/**
 *create author : FZW
 *create date  : 2024/9/18
 *讨论内容禁止发布虚假信息,代购信息,折扣价格,求鉴定等违规内容,如发布将做删帖处理,情节严重者将封 ID，详见论坛发帖规则。
 */
class RichEditorTextProvider(private val listener: EditorCursorListener) :
    BaseItemProvider<RichEditorData>() {

    override val itemViewType = RichEditorType.TEXT.VALUE

    override val layoutId = R.layout.peovider_rich_editor_text

    override fun convert(helper: BaseViewHolder, item: RichEditorData) {
        helper.setIsRecyclable(false)
        val content = item.s1
        val view = helper.getView<EditText>(R.id.ed_input)
        val textWatcher = InputTextWatcher(item, view, helper.absoluteAdapterPosition)
        view.setText(content)
        view.setSelection(content.length)
        if (view.tag != null) {
            view.removeTextChangedListener(textWatcher)
            view.tag = null
        }
        view.onFocusChangeListener = View.OnFocusChangeListener { v, hasFocus ->
            if (hasFocus) {
                ToastUtils.showLong(helper.absoluteAdapterPosition)
                listener.onItemPosition(
                    -1, helper.absoluteAdapterPosition,
                    isAdd = true,
                    false
                )
                view.addTextChangedListener(textWatcher)
                view.tag = textWatcher
            } else {
                view.removeTextChangedListener(textWatcher)
                view.tag = null
            }
        }

        when (item.isMove) {
            true -> {
                view.setBackgroundResource(R.drawable.shape_input)
            }
            false -> {
                view.setBackgroundResource(0)
            }
        }
        if (item.isFocusable) {
            view.post {
                view.requestFocus()
                item.isFocusable = false
            }
        }
    }

    override fun convert(helper: BaseViewHolder, item: RichEditorData, payloads: List<Any>) {
        for (itemPay in payloads) {
            when (itemPay) {
                NotifyType.START_MOVE.VALUE -> {
                    val view = helper.getView<EditText>(R.id.ed_input)
                    view.setBackgroundResource(R.drawable.shape_input)
                }
                NotifyType.END_MOVE.VALUE -> {
                    val view = helper.getView<EditText>(R.id.ed_input)
                    view.setBackgroundResource(0)
                }
            }
        }
    }

    inner class InputTextWatcher(
        private var item: RichEditorData,
        private val view: EditText,
        private val position: Int
    ) : TextWatcher {
        private var previousTextLength = 0
        private var beforeTextLength = 0

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            beforeTextLength = s?.length ?: 0
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            // 当文本变化时计算行数
            val textLength: Int = s?.length ?: 0
            val currentLineCount: Int = view.layout.lineCount
            // 如果文本长度增加，可能需要增加行数
            if (textLength > previousTextLength) {
                // 检查是否需要增加行数
                if (currentLineCount != view.maxLines) {
                    // 增加行数逻辑
                    // 例如：可以通过设置editText.setMaxLines(editText.getMaxLines() + 1); 来增加行数
                }
            }
            previousTextLength = textLength
            val currentLineNumber = getCurrentLineNumber(view)
            LogUtils.d("previousTextLength$previousTextLength")
            LogUtils.d("currentLineNumber$currentLineNumber")

            ToastUtils.showLong(previousTextLength)

        }

        override fun afterTextChanged(s: Editable) {
            item.s1 = s.toString()
            // 文本长度增加表示正在输入，减少表示正在删除
            val isDeleting: Boolean = s.length < beforeTextLength
            if (!isDeleting) {
                //正在输入文本
                if (s.toString().endsWithNewLine()) {
                    listener.onItemPosition(
                        EditorInfo.IME_ACTION_UNSPECIFIED,
                        position,
                        isAdd = true,
                        isDelete = false
                    )
                    replaceInputMessage(item)
                }
            } else {
                //正在删除文本
//                listener.onItemPosition(
//                    -1, position,
//                    isAdd = true,
//                    isDelete = true
//                )
            }
            if (s.toString().isEmpty()) {
                listener.onItemPosition(
                    -1, position,
                    isAdd = true,
                    isDelete = true
                )
            }
        }
    }

    /***获取 EditText 当前所在行数 ***/
    fun getCurrentLineNumber(editText: EditText): Int {
        val layout: Layout? = editText.layout
        if (layout != null) {
            val currentOffset = editText.selectionStart
            return layout.getLineForOffset(currentOffset)
        }
        return 0
    }


    fun String.endsWithNewLine(): Boolean {
        return endsWith("\r\n") || endsWith("\n") || endsWith("\r")
    }

    fun replaceInputMessage(item: RichEditorData) {
        val msg = item.s1
        if (msg.endsWith("\r\n")){
            item.s1 = msg.replace("\r\n","")
        }
        if (msg.endsWith("\n")){
            item.s1 = msg.replace("\n","")
        }
        if (msg.endsWith("\r")){
            item.s1 = msg.replace("\r","")
        }
    }
}